package pdd;

import com.alibaba.fastjson.JSONObject;
import com.openJar.pdd.beans.ShopCat;
import com.openJar.pdd.beans.UsedCatRecord;
import com.openJar.pdd.enums.UploadImgTypeEnum;
import com.openJar.requests.*;
import com.openJar.responses.*;
import com.opentae.data.mall.beans.*;
import com.opentae.data.mall.examples.PddAuthScopExample;
import com.opentae.data.mall.examples.PddShopCatExample;
import com.opentae.data.mall.examples.PddTbCatReferenceExample;
import com.opentae.data.mall.examples.ShiguPddUsercatExample;
import com.opentae.data.mall.interfaces.*;
import com.shigu.beans.UploadImgTask;
import com.shigu.beans.WorkerMan;
import com.shigu.beans.vo.AuthedInfo;
import com.shigu.beans.vo.PddCatsNamesVO;
import com.shigu.component.common.InnerResponse;
import com.shigu.component.common.InnerResponseCodeEnum;
import com.shigu.exceptions.ImgThreadOverloadException;
import com.shigu.main4.tools.RedisIO;
import com.shigu.tools.ExceptionWrapperUtil;
import com.shigu.tools.JsonResponseUtil;
import com.shigu.tools.OSSTool;
import com.shigu.tools.Pingyin;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import pdd.beans.GoodsCats;
import pdd.constant.PddConfig;
import pdd.goods.authorization.cats.AuthorizationCatsRequest;
import pdd.goods.authorization.cats.AuthorizationCatsResponse;
import pdd.internal.util.HttpUtil;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * Created By admin on 2017/12/11/16:29
 * 京东授权接口
 */
@Service
public class PddAuthService {

    private Logger logger = LoggerFactory.getLogger(PddAuthService.class);

    @Resource(name = "tae_mall_pddSessionMapMapper")
    private PddSessionMapMapper pddSessionMapMapper;
    @Resource(name = "tae_mall_pddAuthScopMapper")
    private PddAuthScopMapper pddAuthScopMapper;
    @Resource(name = "tae_mall_shiguPddCatMapper")
    private ShiguPddCatMapper shiguPddCatMapper;
    @Resource(name = "tae_mall_pddTbCatReferenceMapper")
    private PddTbCatReferenceMapper pddTbCatReferenceMapper;
    @Resource(name = "tae_mall_shiguPddUsercatMapper")
    private ShiguPddUsercatMapper shiguPddUsercatMapper;
    @Resource(name = "tae_mall_pddShopCatMapper")
    private PddShopCatMapper pddShopCatMapper;
    @Resource
    private XzPddClient xzPddClient;
    @Resource
    private RedisIO redisIO;
    @Resource
    private OSSTool ossTool;

    /**
     * 获取授权信息，并记录（更新）数据到库
     * @param code
     * @return
     * @throws IOException
     */
    public InnerResponse<AuthedInfo> getAuthedInfo(String code){

        Map<String,String> params = new HashMap<>();
        params.put("client_id", PddConfig.APP_KEY);
        params.put("client_secret", PddConfig.APP_SECRET);
        params.put("grant_type","authorization_code");
        params.put("code",code);
        params.put("redirect_uri",PddConfig.APP_REDIRECT_URI);
        params.put("state",PddConfig.APP_STATE);


         String resStr = HttpUtil.doPost(PddConfig.AUTH_TOKEN_URL, params);
        //是否请求成功
        if (resStr == null) {
            return new InnerResponse<>(InnerResponseCodeEnum.AUTHED_FAILURE);
        }

        InnerResponse<AuthedInfo> innerResponse = new InnerResponse<>();
        JSONObject authedInfoJson = null;
        AuthedInfo authedInfo = null;
        String scopeString = null;
        try {
            authedInfoJson = JSONObject.parseObject(resStr);
            authedInfo = JSONObject.parseObject(resStr,AuthedInfo.class);
            scopeString = authedInfoJson.getString("scope");
            authedInfo.setAuthScope(JSONObject.parseArray(scopeString,String.class));

        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (authedInfo == null || authedInfo.getThirdUid() == null) {
                if (logger.isInfoEnabled()) {
                    logger.info("授权失败>>>>>>>>>>>>  "+resStr);
                }
                return new InnerResponse<>(InnerResponseCodeEnum.AUTHED_FAILURE);
            }
        }

        PddSessionMap pddSessionMap = new PddSessionMap();
        pddSessionMap.setThirdUid(authedInfo.getThirdUid());
        Date now = new Date();
        authedInfo.setAuthTime(now.getTime());

        PddSessionMap sePddSessionMap = pddSessionMapMapper.selectOne(pddSessionMap);
        if (sePddSessionMap == null) {
            pddSessionMap.setThirdUserNick(authedInfo.getThirdUserNick());
            pddSessionMap.setAccessToken(authedInfo.getAccessToken());
            pddSessionMap.setRefreshToken(authedInfo.getRefreshToken());
            pddSessionMap.setAuthTime(now);
            pddSessionMap.setExpiresIn(authedInfo.getExpiresIn());
            pddSessionMap.setGmtCreate(now);
            pddSessionMap.setGmtModify(now);
            pddSessionMapMapper.insertSelective(pddSessionMap);
        }else{
            pddSessionMap.setId(sePddSessionMap.getId());
            pddSessionMap.setAccessToken(authedInfo.getAccessToken());
            pddSessionMap.setRefreshToken(authedInfo.getRefreshToken());
            pddSessionMap.setAuthTime(now);
            pddSessionMap.setExpiresIn(authedInfo.getExpiresIn());
            pddSessionMap.setGmtModify(now);
            pddSessionMapMapper.updateByPrimaryKeySelective(pddSessionMap);
        }
        innerResponse.setCode(InnerResponseCodeEnum.SUCCESS.getCode());
        innerResponse.setData(authedInfo);

        //写auth_scop 发生异常只需记录下日志
        try {
            this.updateScop(authedInfo);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return innerResponse;
    }

    @Transactional
    public void updateScop(AuthedInfo authedInfo){
        if (authedInfo == null || authedInfo.getAuthScope() == null) {
            return;
        }
        List<String> authScope = authedInfo.getAuthScope();
        if (authScope != null && !authScope.isEmpty()) {
            List<PddAuthScop> scops = new ArrayList<>();
            Date now = new Date();
            for (String scop : authScope){
                PddAuthScop pddAuthScop = new PddAuthScop();
                pddAuthScop.setThirdUid(authedInfo.getThirdUid());
                pddAuthScop.setPddScop(scop);
                pddAuthScop.setGmtCreate(now);
                pddAuthScop.setGmtModify(now);

                scops.add(pddAuthScop);
            }
            PddAuthScopExample example = new PddAuthScopExample();
            example.createCriteria().andThirdUidEqualTo(authedInfo.getThirdUid());
            pddAuthScopMapper.deleteByExample(example);
            pddAuthScopMapper.insertListNoId(scops);
        }

    }

    /**
     * 刷新token
     * @param refreshToken 刷新token
     */
    public InnerResponse<AuthedInfo> refreshToken(String refreshToken) {

        if (StringUtils.isBlank(refreshToken)) {
            return new InnerResponse<>(InnerResponseCodeEnum.TOKEN_REFRESH_FAILURE);
        }

        Map<String,String> params = new HashMap<>();
        params.put("client_id",PddConfig.APP_KEY);
        params.put("client_secret", PddConfig.APP_SECRET);
        params.put("grant_type","refresh_token");
        params.put("refresh_token",refreshToken);
        params.put("state",PddConfig.APP_STATE);


        String resStr = HttpUtil.doPost(PddConfig.AUTH_TOKEN_URL, params);
        //是否请求成功
        if (resStr == null) {
            return new InnerResponse<>(InnerResponseCodeEnum.TOKEN_REFRESH_FAILURE);
        }

        JSONObject authedInfoJson = null;
        AuthedInfo authedInfo = null;
        String scopeString = null;
        try {
            authedInfoJson = JSONObject.parseObject(resStr);
            authedInfo = JSONObject.parseObject(resStr,AuthedInfo.class);
            scopeString = authedInfoJson.getString("scope");
            authedInfo.setAuthScope(JSONObject.parseArray(scopeString,String.class));

        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (authedInfo == null || authedInfo.getThirdUid() == null) {
                if (logger.isInfoEnabled()) {
                    logger.info("授权失败>>>>>>>>>>>>  "+resStr);
                }
                return new InnerResponse<>(InnerResponseCodeEnum.TOKEN_REFRESH_FAILURE);
            }
        }

        PddSessionMap pddSessionMap = new PddSessionMap();
        pddSessionMap.setThirdUid(authedInfo.getThirdUid());
        Date now = new Date();
        PddSessionMap sePddSessionMap = pddSessionMapMapper.selectOne(pddSessionMap);
        if (sePddSessionMap == null) {
            return new InnerResponse<>(InnerResponseCodeEnum.TOKEN_REFRESH_FAILURE);
        }

        pddSessionMap.setId(sePddSessionMap.getId());
        pddSessionMap.setAccessToken(authedInfo.getAccessToken());
        pddSessionMap.setRefreshToken(authedInfo.getRefreshToken());
        pddSessionMap.setAuthTime(now);
        pddSessionMap.setExpiresIn(authedInfo.getExpiresIn());
        pddSessionMap.setGmtModify(now);
        pddSessionMapMapper.updateByPrimaryKeySelective(pddSessionMap);

        InnerResponse<AuthedInfo> innerResponse = new InnerResponse<>();
        innerResponse.setCode(InnerResponseCodeEnum.SUCCESS.getCode());
        innerResponse.setData(authedInfo);

        //写auth_scop 发生异常只需记录下日志
        try {
            this.updateScop(authedInfo);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return innerResponse;
    }

    /**
     * 刷新token
     * @param request 请求参数
     * @param response 返回参数
     * @return 授权信息
     */
    public PddRefreshAuthInfoResponse refreshToken(PddRefreshAuthInfoRequest request, PddRefreshAuthInfoResponse response) {
        if (request.getThirdUid() == null) {
            response.setSuccess(false);
            response.setException(ExceptionWrapperUtil.getOpenException("拼多多的用户ID不能为空"));
            return response;
        }
        PddSessionMap pddSessionMap = new PddSessionMap();
        pddSessionMap.setThirdUid(request.getThirdUid());
        pddSessionMap = pddSessionMapMapper.selectOne(pddSessionMap);
        if (pddSessionMap == null) {
            response.setSuccess(false);
            response.setException(ExceptionWrapperUtil.getOpenException("未查询到授权信息"));
            return response;
        }
        InnerResponse<AuthedInfo> infoInnerResponse = this.refreshToken(pddSessionMap.getRefreshToken());
        if (!infoInnerResponse.hasSuccess()) {
            response.setSuccess(false);
            response.setException(ExceptionWrapperUtil.getOpenException("刷新授权失败"));
            return response;
        }
        response.setSuccess(true);
        response.setAccessToken(infoInnerResponse.getData().getAccessToken());

        return response;
    }

    /**
     * 根据pddUid查询授权信息
     * @param request 请求参数
     * @param response 返回参数
     * @return 授权信息
     */
    public PddAuthInfoResponse selAuthInfo(PddAuthInfoRequest request, PddAuthInfoResponse response) {
        if (request.getThirdUid() == null) {
            response.setSuccess(false);
            response.setException(ExceptionWrapperUtil.getOpenException("拼多多的用户ID不能为空"));
            return response;
        }

        PddSessionMap pddSessionMap = new PddSessionMap();
        pddSessionMap.setThirdUid(request.getThirdUid());
        pddSessionMap = pddSessionMapMapper.selectOne(pddSessionMap);
        if (pddSessionMap == null) {
            response.setSuccess(false);
            response.setException(ExceptionWrapperUtil.getOpenException("未查询到授权信息"));
            return response;
        }

        response.setSuccess(true);
        response.setThirdUid(pddSessionMap.getThirdUid());
        response.setThirdUserNick(pddSessionMap.getThirdUserNick());
        response.setAccessToken(pddSessionMap.getAccessToken());
        response.setRefreshToken(pddSessionMap.getRefreshToken());
        response.setAuthTime(pddSessionMap.getAuthTime().getTime());
        response.setExpiresIn(pddSessionMap.getExpiresIn());

        return response;
    }


    /**
     * 获取类目层级名
     * @param request 请求
     * @param response 返回
     * @return 0.0.1
     */
    public PddCatsNamesResponse pddCatsNames(PddCatsNamesRequest request, PddCatsNamesResponse response) {
        PddCatsNamesVO vo = pddCatsInfo(request.getCatId());
        if (vo == null) {
            response.setSuccess(false);
            response.setException(ExceptionWrapperUtil.getOpenException("未查询到类目信息"));
            return response;
        }
        response.setSuccess(true);
        response.setCatNames(vo.getCatNames());
        response.setAllCids(vo.getAllCids());
        response.setLastCatName(vo.getLastCatName());
        return response;
    }

    /**
     *  查询类目层级信息
     * @param cid 类目id
     * @return 类目层级信息
     */
    public PddCatsNamesVO pddCatsInfo(Long cid){
        ShiguPddCat shiguPddCat = pddCats(cid);
        if (shiguPddCat == null) {
           return null;
        }
        String catNames = shiguPddCat.getCatName();
        String catIds =  ""+shiguPddCat.getCatId();

        ShiguPddCat parentCat = null;
        Long parentCatId = shiguPddCat.getParentId();
        while (true){
            parentCat = pddCats(parentCatId);
            if (parentCat == null) {
                break;
            }
            parentCatId = parentCat.getParentId();
            catNames = parentCat.getCatName() + " > " + catNames;
            catIds = parentCat.getCatId() + "," + catIds;
            if (parentCat.getCatLevel() == 1 && parentCat.getIsParent() == 1) {
                break;
            }
        }

        PddCatsNamesVO vo = new PddCatsNamesVO();
        vo.setCatNames(catNames);
        vo.setAllCids(catIds);
        vo.setLastCatName(shiguPddCat.getCatName());

        return vo;

    }

    /**
     * 获取类目层级名
     * @param catId 类目id
     * @return 0.0.1
     */
    public ShiguPddCat pddCats(Long catId) {
        ShiguPddCat shiguPddCat = new ShiguPddCat();
        shiguPddCat.setCatId(catId);
        shiguPddCat = shiguPddCatMapper.selectOne(shiguPddCat);
        if (shiguPddCat == null) {
            return null;
        }
        return shiguPddCat;
    }

    /**
     * 获取第三级类目
     *  拼多多只存在四级类目，二级类目全部有子集类目
     * @param request 请求
     * @param response 返回
     * @return 第三级类目id
     */
    public SelThirdLevelCidResponse selThirdLevelCid(SelThirdLevelCidRequest request, SelThirdLevelCidResponse response) {
        ShiguPddCat shiguPddCat = new ShiguPddCat();
        shiguPddCat.setCatId(request.getPddCid());
        shiguPddCat = shiguPddCatMapper.selectOne(shiguPddCat);
        if (shiguPddCat == null) {
            response.setSuccess(false);
            response.setException(ExceptionWrapperUtil.getOpenException("类目不存在"));
            return response;
        }
        if (shiguPddCat.getCatLevel() < 3) {
            response.setSuccess(false);
            response.setException(ExceptionWrapperUtil.getOpenException("只能根据第三、第四级类目查询"));
            return response;
        }
        if (shiguPddCat.getCatLevel() == 3) {
            response.setSuccess(true);
            response.setThirdLevelCid(shiguPddCat.getCatId());
            return response;
        }
        //第四级
        response.setSuccess(true);
        response.setThirdLevelCid(shiguPddCat.getParentId());
        return response;
    }

    /**
     *  添加用户上传类目记录
     * @param request 请求
     * @param response 返回
     * @return 成功失败
     */
    public AddUsedCatRecordResponse addUsedCatRecord(AddUsedCatRecordRequest request, AddUsedCatRecordResponse response) {
        ShiguPddUsercatExample example = new ShiguPddUsercatExample();
        example.createCriteria().andXzUserIdEqualTo(request.getXzUserId()).andCidEqualTo(request.getPddCid());
        List<ShiguPddUsercat> shiguPddUsercats = shiguPddUsercatMapper.selectByExample(example);
        if (shiguPddUsercats != null && shiguPddUsercats.size() > 0) {
            response.setSuccess(true);
            return response;
        }

        PddCatsNamesVO pddCatsNamesVO = pddCatsInfo(request.getPddCid());
        if (pddCatsNamesVO == null) {
            response.setSuccess(false);
            response.setException(ExceptionWrapperUtil.getOpenException("类目不存在"));
            return response;
        }
        ShiguPddUsercat shiguPddUsercat = new ShiguPddUsercat();
        shiguPddUsercat.setCid(request.getPddCid());
        shiguPddUsercat.setXzUserId(request.getXzUserId());
        shiguPddUsercat.setCname(pddCatsNamesVO.getLastCatName());
        shiguPddUsercat.setCnamePy(Pingyin.getPingYin(pddCatsNamesVO.getLastCatName()));
        shiguPddUsercat.setShowName(pddCatsNamesVO.getCatNames());
        shiguPddUsercat.setAllcids(pddCatsNamesVO.getAllCids());
        shiguPddUsercat.setCreated(new Date());

        shiguPddUsercatMapper.insert(shiguPddUsercat);

        response.setSuccess(true);
        return response;
    }

    /**
     *  搜索用户上传类目记录
     * @param request 请求
     * @param response 返回
     * @return 成功失败
     */
    public SelUsedCatRecordResponse selUsedCatRecord(SelUsedCatRecordRequest request, SelUsedCatRecordResponse response) {
        ShiguPddUsercatExample example = new ShiguPddUsercatExample();
        example.setStartIndex(request.getStartIndex() == null ? 0 : request.getStartIndex());
        example.setEndIndex(request.getSize() == null ? 5 : request.getSize());
        ShiguPddUsercatExample.Criteria criteria = example.createCriteria();
        criteria.andXzUserIdEqualTo(request.getXzUserId());
        if (StringUtils.isNotBlank(request.getCatName())) {
            criteria.andCnamePyLike("%"+Pingyin.getPingYin(request.getCatName())+"%");
        }

        List<ShiguPddUsercat> shiguPddUsercats = shiguPddUsercatMapper.selectByExample(example);
        if (shiguPddUsercats == null) {
            response.setSuccess(true);
            return response;
        }

        List<UsedCatRecord> usedCatRecords = shiguPddUsercats.stream().map(item -> {
            UsedCatRecord usedCatRecord = new UsedCatRecord();
            usedCatRecord.setCid(item.getCid());
            usedCatRecord.setAllcids(item.getAllcids());
            usedCatRecord.setShowName(item.getShowName());
            return usedCatRecord;
        }).collect(Collectors.toList());
        response.setSuccess(true);
        response.setUsedCatRecords(usedCatRecords);
        return response;
    }

    /**
     *  根据星座cid换取拼多多cid
     * @param request 请求
     * @param response 返回
     * @return 成功失败
     */
    public SelPddCidByXzCidResponse selPddCidByXzCid(SelPddCidByXzCidRequest request, SelPddCidByXzCidResponse response) {
        PddTbCatReferenceExample example = new PddTbCatReferenceExample();
        example.createCriteria().andTbCatIdEqualTo(request.getXzCid());

        List<PddTbCatReference> pddTbCatReferences = pddTbCatReferenceMapper.selectByExample(example);
        if (pddTbCatReferences == null || pddTbCatReferences.isEmpty()) {
            response.setSuccess(false);
            response.setException(ExceptionWrapperUtil.getOpenException("未查询打对应类目信息"));
            return response;
        }
        if (pddTbCatReferences.size() > 1){
            pddTbCatReferences = pddTbCatReferences.stream()
                    .filter(item-> item.getSex().intValue() == request.getSex().intValue()).collect(Collectors.toList());
        }
        response.setSuccess(true);
        response.setPddCid(pddTbCatReferences.get(0).getPddCatId());
        return response;
    }

    /**
     *  上传图片
     * @param request 请求
     * @param response 返回
     * @return 成功失败
     */
    public PddUploadImgResponse pddUploadImg(PddUploadImgRequest request, PddUploadImgResponse response) {
        PddSessionMap pddSessionMap = new PddSessionMap();
        pddSessionMap.setThirdUid(request.getPddUid());

        pddSessionMap = pddSessionMapMapper.selectOne(pddSessionMap);
        if (pddSessionMap == null) {
            response.setSuccess(false);
            response.setException(ExceptionWrapperUtil.getOpenException("请先登陆"));
            return response;
        }

        final String tempCode = request.getTempCode();
        if (UploadImgTypeEnum.DETAILS.getType().equals(request.getType())){
            Integer uplodedNum = redisIO.get(request.getTempCode(),Integer.class);
            if (uplodedNum != null && uplodedNum >= 20) {
//                response.setSuccess(false);
//                response.setException(ExceptionWrapperUtil.getOpenException("详情图已上传完毕"));
//                return response;

                //重复点击上传需要重用tempCode 前端限制大于20不再请求
                redisIO.del(tempCode);
            }
        }

        UploadImgTask task = new UploadImgTask();
        task.setUrl(request.getImgUrl());
        task.setType(request.getType());
        task.setAccessToken(pddSessionMap.getAccessToken());
        task.setOssTool(ossTool);
        task.setTempCode(request.getTempCode());

        List<String> imgUrls = null;
        try {
            imgUrls = WorkerMan.getInstance().start(task);
        } catch (ImgThreadOverloadException e) {
            e.printStackTrace();
            response.setSuccess(false);
            response.setException(ExceptionWrapperUtil.getOpenException("非法请求,图片搬家调用超载"));
            return response;
        } catch (Exception e){
            e.printStackTrace();
            response.setSuccess(false);
            response.setException(ExceptionWrapperUtil.getOpenException("图片上传失败"));
            return response;
        }


        if (UploadImgTypeEnum.DETAILS.getType().equals(request.getType())){
            Integer uplodedNum = redisIO.get(request.getTempCode(),Integer.class);
            if (uplodedNum == null) {
                uplodedNum = 0;
            }
            int totalNum = uplodedNum + imgUrls.size();
            if (totalNum > 20) {//多余的丢弃
                imgUrls = imgUrls.stream().limit(20 - uplodedNum).collect(Collectors.toList());
                totalNum = 20;
            }
            redisIO.putTemp(tempCode,totalNum,600);//存10分钟
            response.setNum(totalNum);
        }
        response.setTempCode(request.getTempCode());
        response.setPddImgUrls(imgUrls);
        response.setSuccess(true);
        return response;
    }

    /**
     * 同步店内类目
     * @param pddUid 拼多多用户id
     */
    public boolean shouldUpdateShopCat(Long pddUid) {
        //查店内类目，查不到去更新
        PddShopCatExample example = new PddShopCatExample();
        example.createCriteria().andPddUidEqualTo(pddUid);
        int count = pddShopCatMapper.countByExample(example);
        if (count > 0 ) {
            return false;
        }
        return true;
    }


    /**
     * 同步店内类目
     * @param pddUid 拼多多用户id
     */
    @Transactional
    public Future<net.sf.json.JSONObject> updateShopCat(Long pddUid) {

        PddSessionMap pddSessionMap = new PddSessionMap();
        pddSessionMap.setThirdUid(pddUid);
        pddSessionMap = pddSessionMapMapper.selectOne(pddSessionMap);
        if (pddSessionMap == null) {
            return new AsyncResult<net.sf.json.JSONObject>( JsonResponseUtil.error("店内类目更新失败"));
        }

        PddShopCatExample example = new PddShopCatExample();
        example.createCriteria().andPddUidEqualTo(pddSessionMap.getThirdUid());
        pddShopCatMapper.deleteByExample(example);

        Long parentCid = 0L;
        catsGet(pddUid,parentCid,pddSessionMap.getAccessToken());

//        return JsonResponseUtil.success();
        return new AsyncResult<net.sf.json.JSONObject>( JsonResponseUtil.success());
    }

    @Transactional
    public void catsGet(final Long pddUid,final Long parentCid,final String accessToken){
        AuthorizationCatsRequest request = new AuthorizationCatsRequest();
        request.setParent_cat_id(parentCid);
        AuthorizationCatsResponse response = xzPddClient.openClient(accessToken).excute(request);

        if (response.getSuccess()) {
            if (response.getGoodsCatsList() != null && response.getGoodsCatsList().size() > 0) {
                //将此类目is_parent值修改
                PddShopCat pddShopCat = new PddShopCat();
                pddShopCat.setPddUid(pddUid);
                pddShopCat.setCatId(parentCid);
                pddShopCat = pddShopCatMapper.selectOne(pddShopCat);
                if (pddShopCat != null) {
                    pddShopCat.setIsParent(1);
                    pddShopCat.setGmtModify(new Date());
                    pddShopCatMapper.updateByPrimaryKey(pddShopCat);
                }

                List<GoodsCats> goodsCatsList = response.getGoodsCatsList();
                if (goodsCatsList != null && goodsCatsList.size() > 0) {
                    List<PddShopCat> pddShopCats = new ArrayList<>();
                    Date now = new Date();
                    goodsCatsList.stream().forEach(item -> {
                        PddShopCat shopCat = new PddShopCat();
                        shopCat.setPddUid(pddUid);
                        shopCat.setCatId(item.getCatId());
                        shopCat.setCatName(item.getCatName());
                        shopCat.setParentId(parentCid);
                        shopCat.setGmtCreate(now);
                        shopCat.setGmtModify(now);
                        shopCat.setIsParent(0);

                        pddShopCats.add(shopCat);
                    });
                    if (pddShopCats.size() > 0) {
                        pddShopCatMapper.insertListNoId(pddShopCats);
                    }
//                    Integer.parseInt("abc");
                    for (PddShopCat shopCat : pddShopCats) {
//                        try {
//                            TimeUnit.SECONDS.sleep(1);
//                        } catch (InterruptedException e) {
//                            e.printStackTrace();
//                        }
                        catsGet(pddUid,shopCat.getCatId(),accessToken);
                    }
                }
            }
        }
    }

    /**
     *  获取店内类目
     * @param request 请求
     * @param response 返回
     * @return 成功失败
     */
    public SelAuthorizationCatsResponse selAuthorizationCats(SelAuthorizationCatsRequest request, SelAuthorizationCatsResponse response) {
        PddShopCatExample example = new PddShopCatExample();
        example.createCriteria().andPddUidEqualTo(request.getPddUid()).andParentIdEqualTo(request.getParentCid());
        List<PddShopCat> pddShopCats = pddShopCatMapper.selectByExample(example);
        if (pddShopCats == null || pddShopCats.isEmpty()) {
            response.setSuccess(true);
            return response;
        }

        List<ShopCat> shopCats = pddShopCats.stream().map(item -> {
            ShopCat shopCat = new ShopCat();
            shopCat.setCatId(item.getCatId());
            shopCat.setCatName(item.getCatName());
            shopCat.setIsParent(item.getIsParent());
            return shopCat;
        }).collect(Collectors.toList());

        response.setSuccess(true);
        response.setShopCats(shopCats);
        return response;
    }

}
